<template>
	<coreshop-page title="分享" mode="left">
		<view class="share-poster-box">
			<image class="img" :src="state.imgSrc" mode="widthFix"></image>
			<LPainter ref="painter" custom-style="position: fixed; left: 200%"
				css="width: 750rpx;  padding-bottom: 40rpx;border-radius: 0rpx; background: linear-gradient(#ff971b 0%, #ff5000 100%)">
				<lpainterimage :src="state.userInfo?.avatarImage"
					css="margin-left: 40rpx; margin-top: 40rpx; width: 100rpx;  height: 100rpx; border-radius: 50%;" />
				<lpainterView css="margin-top: 40rpx; padding-left: 20rpx; display: inline-block">
					<lpainterText :text="state.userInfo?.nickName"
						css="display: block; padding-bottom: 10rpx; color: #fff; font-size: 32rpx; fontWeight: bold" />
					<lpainterText :text="state.shareData.describe" css="color: #fff; font-size: 27rpx" />
				</lpainterView>
				<lpainterView
					css="margin-left: 40rpx; margin-top: 30rpx; padding: 30rpx; box-sizing: border-box; background: #fff; border-radius: 16rpx; width: 670rpx; box-shadow: 0 20rpx 58rpx rgba(0,0,0,.15)">
					<lpainterimage :src="state.shareData.image"
						css="object-fit: cover; object-position: 50% 50%; width: 606rpx; height: 606rpx; border-radius: 12rpx;" />
					<lpainterView
						css="margin-top: 30rpx; color: #FF0000; font-weight: bold; font-size: 28rpx; line-height: 1em;"
						v-if="state.showPrice">
						<lpainterText text="￥" css="vertical-align: bottom" />
						<lpainterText :text="state.shareData.price" css="vertical-align: bottom; font-size: 58rpx" />
						<lpainterText text="元" css="vertical-align: bottom" />
						<lpainterText v-if="state.shareData.mktprice > 0" :text="'￥' + state.shareData.mktprice"
							css="vertical-align: bottom; padding-left: 20rpx; font-weight: normal; text-decoration: line-through; color: #999999" />
					</lpainterView>
					<lpainterView
						css="margin-top: 10rpx; color: #FF0000; font-weight: bold; font-size: 28rpx; line-height: 1em;">
						<lpainterText :text="state.shareData.storeDesc"
							css="vertical-align: bottom; font-size: 48rpx" />
					</lpainterView>
					<lpainterView css="margin-top: 30rpx; font-size: 26rpx; color: #8c5400"
						v-if="state.shareData.showPinTuanArguments">
						<lpainterText :text="'截止：' + state.shareData.endTime"
							css="color: #212121; background: #ffb400; padding:8rpx 10rpx;border-radius:12rpx" />
						<lpainterText :text="state.shareData.peopleNumber + '人团'"
							css="margin-left: 16rpx; background: #fff4d9; padding:8rpx 10rpx;border-radius:12rpx text-decoration: line-through;" />
					</lpainterView>
					<lpainterView css="margin-top: 30rpx; font-size: 26rpx; color: #8c5400"
						v-if="state.shareData.showGroupPurchaseSeckillArguments">
						<lpainterText :text="'截止：' + state.shareData.endTime"
							css="color: #212121; background: #ffb400; padding:8rpx 20rpx;border-radius:12rpx" />
					</lpainterView>
					<lpainterView css="width: 570rpx;margin-top: 30rpx; font-size: 26rpx; color: #8c5400">
						<lpainterText :text="state.shareData.brief"
							css=" background: #fff4d9; padding:8rpx 20rpx; border-radius:12rpx" />
					</lpainterView>
					<lpainterView css="margin-top: 30rpx">
						<lpainterText
							css="line-clamp: 3; color: #333333; line-height: 1.8em; font-size: 32rpx; width: 458rpx; padding-right:32rpx; box-sizing: border-box"
							:text="state.shareData.name"></lpainterText>
						<lpainterimage :src="state.poster" css="width: 150rpx; height: 150rpx;" />
					</lpainterView>
				</lpainterView>
			</LPainter>
            <!-- #ifdef MP  -->
			<view class="tip-box" v-if="state.imgSrc">
				注：如果您下载失败，或者以前拒绝过弹出的授权相册提醒，请点击右上角三个点，进入【设置】页面，开启【添加到相册】功能。
			</view>
            <!-- #endif -->
			<view class="btn-box">
				<view class="btn">
					<view class="back" @click="handlenNavigateBack">返回上一页</view>
					<view class="save" @click="handlesavePoster">保存到本地</view>
				</view>
			</view>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref, watch, nextTick } from 'vue';
	import type { Response, UserInfoType } from '@/core/models';
	import { onLoad } from '@dcloudio/uni-app';
	import { UserToken } from '@/core/consts';
	import { handleShowToast, handleStaticResources, handleAuthorize } from '@/core/utils';
	import { ShareEnum } from '@/core/enum';
	import { queryUserInfo, queryActivityDetial, queryDistributionStoreInfo, queryAgentInfo, queryGoodsDetail, queryPinTuanGoodsDetail, queryServiceDetail } from '@/core/api';
	import LPainter from '@/uni_modules/lime-painter/components/l-painter/l-painter.vue';
	import lpainterimage from '@/uni_modules/lime-painter/components/l-painter-image/l-painter-image.vue';
	import lpainterView from '@/uni_modules/lime-painter/components/l-painter-view/l-painter-view.vue';
	import lpainterText from '@/uni_modules/lime-painter/components/l-painter-text/l-painter-text.vue';

	interface QueryParams {
		posterUrl : string;
		shareType : number;
		[key : string] : any;
	}
	const painter = ref();
	const state = reactive<{
		userInfo : UserInfoType,
		imgSrc : string;
		poster : string;
		shareType : number;
		shareData : any;
		showPrice : boolean;
	}>({
		userInfo: {},
		imgSrc: "",
		poster: "",
		shareType: 1,
		shareData: {},
		showPrice: true,
	})

	onLoad((query : QueryParams) => {
		getUserInfo();

		state.poster = decodeURIComponent(query.posterUrl);
		state.shareType = query.shareType;
		uni.showLoading({
			title: '生成中...'
		});
		handleShare(query);
	})

	watch(() => state.imgSrc, (newVal : string) => {
		if (newVal) {
			uni.hideLoading();
		}
	})

	/** 获取用户信息 */
	const getUserInfo = async () => {
		const userInfo : Response<UserInfoType> = await queryUserInfo();
		state.userInfo = userInfo?.data;
	}

	/** 处理分享类型获取数据 */
	const handleShare = (query : QueryParams) => {
		if (state.shareType == ShareEnum.goods) {
			/** 获取商品详情 */
			getGoodsDetail(query)
		} else if (state.shareType == ShareEnum.pinTuan || state.shareType == ShareEnum.addPinTuan) {
			/** 获取活动拼团详情 */
			getActivityPinTuan(query);
		} else if (state.shareType == ShareEnum.serviceGoods) {
			/** 获取服务商品详情 */
			getActivityServiceGoods(query);
		} else if (state.shareType == ShareEnum.seckill) {
			/** 获取活动秒杀 */
			getActivitySeckill(query);
		} else if (state.shareType == ShareEnum.group) {
			/** 获取活动团购 */
			getActivityGroup(query);
		} else if (state.shareType == ShareEnum.inv) {
			/** 获取分销店铺信息 */
			getDistributionStoreInfo(query);
		} else if (state.shareType == ShareEnum.agent) {
			/** 获取理商进度状态 */
			getAgentInfo(query);
		}
		nextTick(() => {
			handleCanvasToTempFilePath();
		})
	}

	const handleCanvasToTempFilePath = () => {
		painter.value.canvasToTempFilePathSync({
			fileType: "jpg",
			// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
			pathType: 'url',
			quality: 1,
			success: (res : any) => {
				state.imgSrc = res.tempFilePath;
			},
		});
	}

	/** 获取商品详情 */
	const getGoodsDetail = async (query : QueryParams) => {
		const goodsDetail : Response<any> = await queryGoodsDetail({ id: query.goodsId });
		if (goodsDetail.status) {
			state.shareData.image = goodsDetail.data?.image;
			state.shareData.brief = goodsDetail.data?.brief;
			state.shareData.name = goodsDetail.data?.name;
			state.shareData.price = goodsDetail.data?.product?.price;
			state.shareData.mktprice = goodsDetail.data?.product?.mktprice;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 获取活动拼团 */
	const getActivityPinTuan = async (query : QueryParams) => {
		const goodsDetail : Response<any> = await queryPinTuanGoodsDetail({ id: query.groupId, data: false });
		if (goodsDetail.status) {
			state.shareData.describe = "为您推荐了一个拼团活动";
			state.shareData.image = goodsDetail.data?.image;
			state.shareData.brief = goodsDetail.data?.name;
			state.shareData.name = goodsDetail.data?.pinTuanRule?.name;
			state.shareData.price = goodsDetail.data?.pinTuanPrice;
			state.shareData.mktprice = goodsDetail.data?.mktprice;

			state.shareData.showPinTuanArguments = true;
			state.shareData.endTime = goodsDetail.data?.pinTuanRule?.endTime;
			state.shareData.peopleNumber = goodsDetail.data?.pinTuanRule?.peopleNumber;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 获取服务商品详情  */
	const getActivityServiceGoods = async (query : QueryParams) => {
		const goodsDetail : Response<any> = await queryServiceDetail({ id: parseInt(query.serviceGoodsId), data: false, });
		if (goodsDetail.status) {
			state.shareData.describe = "为您推荐了一个服务商品";
			state.shareData.image = goodsDetail.data?.thumbnail;
			state.shareData.brief = goodsDetail.data?.description;
			state.shareData.name = goodsDetail.data?.title;
			state.shareData.price = goodsDetail.data?.money;
			state.shareData.mktprice = goodsDetail.data?.mktprice;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 获取代理商进度状态 */
	const getAgentInfo = async (query : QueryParams) => {
		const goodsDetail : Response<any> = await queryAgentInfo({ id: query.store });
		if (goodsDetail.status) {
			state.shareData.describe = '共有' + goodsDetail.data?.totalGoods + '件商品供您选择';
			state.shareData.name = goodsDetail.data?.storeDesc ? goodsDetail.data?.storeDesc : "欢迎您访问我的店铺";
			state.shareData.storeDesc = goodsDetail.data?.storeName ? goodsDetail.data?.storeName : "我的店铺";
			state.shareData.image = goodsDetail.data?.storeLogo ? goodsDetail.data?.storeLogo : handleStaticResources('/static/images/common/empty.png');
			state.showPrice = false;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 获取分销店铺信息 */
	const getDistributionStoreInfo = async (query : QueryParams) => {
		const goodsDetail : Response<any> = await queryDistributionStoreInfo({ id: query.store });
		if (goodsDetail.status) {
			state.shareData.describe = '共有' + goodsDetail.data?.totalGoods + '件商品供您选择';
			state.shareData.name = goodsDetail.data?.storeDesc ? goodsDetail.data?.storeDesc : "欢迎您访问我的店铺";
			state.shareData.storeDesc = goodsDetail.data?.storeName ? goodsDetail.data?.storeName : "我的店铺";
			state.shareData.image = goodsDetail.data?.storeLogo ? goodsDetail.data?.storeLogo : handleStaticResources('/static/images/common/empty.png');
			state.showPrice = false;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 获取秒杀详情 */
	const getActivitySeckill = async (query : QueryParams) => {
		let data = {
			id: query.groupId,
			type: state.shareType,
			needSku: true,
		}
		if (uni.getStorageSync(UserToken)) {
			data['token'] = uni.getStorageSync(UserToken);
		}
		const goodsDetail : Response<any> = await queryActivityDetial(data);
		if (goodsDetail.status) {
			state.shareData.describe = "为您推荐了一个秒杀";
			state.shareData.image = goodsDetail.data?.image;
			state.shareData.brief = goodsDetail.data?.brief;
			state.shareData.name = goodsDetail.data?.name;
			state.shareData.price = goodsDetail.data?.product?.price;
			state.shareData.mktprice = goodsDetail.data?.product?.mktprice;

			state.shareData.showGroupPurchaseSeckillArguments = true;
			state.shareData.endTime = goodsDetail.data?.groupEndTime;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 获取团购详情 */
	const getActivityGroup = async (query : QueryParams) => {
		let data = {
			id: query.groupId,
			type: state.shareType,
			needSku: true,
		}
		if (uni.getStorageSync(UserToken)) {
			data['token'] = uni.getStorageSync(UserToken);
		}
		const goodsDetail : Response<any> = await queryActivityDetial(data);
		if (goodsDetail.status) {
			state.shareData.describe = "为您推荐了一个团购";
			state.shareData.image = goodsDetail.data?.image;
			state.shareData.brief = goodsDetail.data?.brief;
			state.shareData.name = goodsDetail.data?.name;
			state.shareData.price = goodsDetail.data?.product?.price;
			state.shareData.mktprice = goodsDetail.data?.product?.mktprice;

			state.shareData.showGroupPurchaseSeckillArguments = true;
			state.shareData.endTime = goodsDetail.data?.groupEndTime;
		} else {
			handleShowToast(goodsDetail.msg, 'none', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	}

	/** 返回上一页 */
	const handlenNavigateBack = () => {
		uni.navigateBack();
	}

	/** 保存到本地 */
	const handlesavePoster = async () => {
		// #ifdef APP-PLUS || APP-PLUS-NVUE
		uni.getImageInfo({
			src: state.imgSrc,
			success(res : any) {
				uni.saveImageToPhotosAlbum({
					filePath: res.path,
					success() {
						handleShowToast('保存成功', 'success');
					},
					fail() {
						handleShowToast('图片保存失败', 'error');
					}
				});
			},
			fail() {
				handleShowToast('下载失败', 'error');
			}
		})
		// #endif

		// #ifdef MP  
		let authorizeRes : boolean = await handleAuthorize({ scope: 'writePhotosAlbum' });
		if (authorizeRes) {
			uni.saveImageToPhotosAlbum({
				filePath: state.imgSrc,
				success() {
					handleShowToast('保存成功', 'success');
				},
				fail() {
					handleShowToast('图片保存失败', 'error');
				}
			});
		}
		// #endif 
	}
</script>
<style lang="scss" scoped>
	@import './sharePoster.scss';
</style>